import React, { Component, Fragment } from 'react';
import { connect } from 'react-redux';
import { receiveWebsocketData } from './reducer';

let SocketHeartBeat;
let ws;
let token = localStorage.getItem('x-auth-token');

class WebsocketClass extends Component {
    state = {
        isWs: false
    }

    componentDidMount() {
        let url = 'wss://onlabo.cn/wss/?' + token;
        if (this.props.isOpen) {
            this.WSConnect(url);
        }
    }

    componentWillUnmount() {
        this.WSDisconnect();
    }

    render() {
        return (
            <Fragment>
            </Fragment>
        )
    }

    WSConnect = (url) => {

        try {
            if (!ws) {
                ws = new WebSocket(url);
            }
        } catch (err) {
            console.log('websocket连接失败', err);
        }

        this.initWebsocket(url)

    }

    initWebsocket = (url) => {

        ws.onopen = () => {
            this.setState({ isWs: true });
            this.heartCheck(url);
        }

        ws.onmessage = (message) => {
            this.props.setWebsocketData(JSON.parse(message.data))
        }

        ws.onerror = (err) => {
            console.log('webSocket遇到异常', err);
            this.reconnect(url)
        }

        ws.onclose = () => {
            this.setState({ isWs: false })
        }

    }



    reconnect = (url) => {
        if (this.state.isWs) return;
        this.setState({ isWs: true })
        setTimeout(() => {
            this.WSConnect(url);
            this.setState({ isWs: false })
        }, 2000);
    }

    heartCheck = (url) => {
        SocketHeartBeat = setTimeout(() => {
            clearTimeout(SocketHeartBeat)
            this.heartCheck(url)
            if (this.state.isWs) {
                this.WSSend();
                console.log('socket连接成功，开始心跳，砰砰砰...');
            } else {
                console.log('socket连接失败，现在开始重连...');
                ws = undefined;
                this.WSConnect(url);
            }
        }, 10000);
    }

    WSSend = () => {

        let sendData = {
            type: 'heart',
            data: { "message": "WS心跳数据发送" },
            from: token
        }
        ws.send(JSON.stringify(sendData))
    }

    WSDisconnect = () => {
        clearTimeout(SocketHeartBeat);
        if (ws) {
            ws.close();
            ws = undefined
        }
    }

}

const mapStateToProps = ({ websockets }) => ({
    websocketDatas: websockets.websocketData
})

const mapDispatchToProps = (dispatch) => ({
    setWebsocketData(data) {
        dispatch(receiveWebsocketData(data))
    }
})



export default connect(mapStateToProps, mapDispatchToProps)(WebsocketClass);